/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View;

import Controller.ControladorCR;
import Controller.ControladorDentista;
import Controller.ControladorPaciente;
import Model.ContasReceber;
import VO.AgendamentoVO;
import controller.ControladorAgendamento;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.table.DefaultTableModel;
import model.Agendamento;

/**
 *
 * @author Giovana
 */
public class AgendamentoView extends javax.swing.JFrame {
    ControladorDentista ctrDentista = new ControladorDentista();    
    ControladorPaciente ctrPaciente = new ControladorPaciente();
    ControladorAgendamento ctrAgendamento = new ControladorAgendamento();
    ControladorCR ctrCR = new ControladorCR();
    String codAg;
    /**
     * Creates new form AgendamentoView
     */
    public AgendamentoView() {
        initComponents();
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        cbPacientes = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        cbDentistas = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtHora = new javax.swing.JTextField();
        btAgendar = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        tbAgendamentos = new javax.swing.JTable();
        jLabel6 = new javax.swing.JLabel();
        txtMinuto = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        btAlterar = new javax.swing.JButton();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel1.setText("AGENDAMENTO");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(155, 155, 155)
                .addComponent(jLabel1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));

        jLabel2.setText("Paciente: ");

        cbPacientes.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione..." }));

        jLabel3.setText("Dentista:");

        cbDentistas.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione..." }));

        jLabel4.setText("Data:");

        jLabel5.setText("Horario:");

        btAgendar.setText("Agendar");
        btAgendar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                btAgendarMousePressed(evt);
            }
        });

        tbAgendamentos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tbAgendamentos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tbAgendamentosMousePressed(evt);
            }
        });
        jScrollPane2.setViewportView(tbAgendamentos);

        jLabel6.setText("Pesquisar por Data:");

        jLabel7.setText(":");

        jButton1.setText("Consulta Realizada");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jButton1MousePressed(evt);
            }
        });
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        btAlterar.setText("Alterar");
        btAlterar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                btAlterarMousePressed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(9, 9, 9)
                        .addComponent(jLabel6)))
                .addGap(29, 29, 29))
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(cbDentistas, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(cbPacientes, javax.swing.GroupLayout.Alignment.LEADING, 0, 268, Short.MAX_VALUE))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel2Layout.createSequentialGroup()
                                        .addGap(133, 133, 133)
                                        .addComponent(jLabel5)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                        .addComponent(btAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(20, 20, 20)))
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jButton1)
                                    .addGroup(jPanel2Layout.createSequentialGroup()
                                        .addComponent(txtHora, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 6, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txtMinuto, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(btAgendar, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(261, 261, 261)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cbPacientes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cbDentistas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(20, 20, 20)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel5)
                        .addComponent(txtHora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(txtMinuto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel7)))
                .addGap(32, 32, 32)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(btAgendar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btAlterar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(51, 51, 51)
                .addComponent(jLabel6)
                .addGap(35, 35, 35)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btAgendarMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btAgendarMousePressed
        Agendamento ag = new Agendamento();
        
        String dadosDentista[] = cbDentistas.getSelectedItem().toString().split("-");
        String dadosPaciente[] = cbPacientes.getSelectedItem().toString().split("-");
        
        ag.setCroDentista(Integer.parseInt(dadosDentista[0]));
        ag.setCodPaciente(Integer.parseInt(dadosPaciente[0]));
        ag.setData((Date)dtAgendamento.getValue());
        ag.setHora(Integer.parseInt(txtHora.getText()));
        ag.setMinuto(Integer.parseInt(txtMinuto.getText()));
        
        ctrAgendamento.registrarAgendamento(ag);
        cbPacientes.setSelectedItem(0);
        cbDentistas.setSelectedItem(0);
        txtHora.setText("");
        txtMinuto.setText("");  
        
        ArrayList<AgendamentoVO> lista = ctrAgendamento.obterAgendamentos();
        carregarTabela(lista);
    }//GEN-LAST:event_btAgendarMousePressed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        carregarComboDentista();
        carregarComboPaciente();
        
        ArrayList<AgendamentoVO> lista = ctrAgendamento.obterAgendamentos();
        carregarTabela(lista);
    }//GEN-LAST:event_formWindowOpened

    private void tbAgendamentosMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbAgendamentosMousePressed
        int linha = tbAgendamentos.getSelectedRow();
        String nomeDentista = tbAgendamentos.getModel().getValueAt(linha, 1).toString();
        String croDentista = tbAgendamentos.getModel().getValueAt(linha, 6).toString();
        cbDentistas.setSelectedItem(croDentista + "-" + nomeDentista);
        
        String nomePaciente = tbAgendamentos.getModel().getValueAt(linha, 2).toString();
        String codPaciente = tbAgendamentos.getModel().getValueAt(linha, 5). toString();
        cbPacientes.setSelectedItem(codPaciente + "-" + nomePaciente);
        
        codAg = tbAgendamentos.getModel().getValueAt(linha, 0).toString();
        //CONVERTENDO A DATA DE FORMATO STRING PARA DATE
        String[] data = tbAgendamentos.getModel().getValueAt(linha, 3).toString().split(" ");
        String pattern = "yyyy-MM-dd";
        DateFormat df = new SimpleDateFormat(pattern);
        try{
            Date date = df.parse(data[0]);
            dtAgendamento.setValue(date);
        }catch (Exception ex){
            //imprimindo mensagem de erro
            ex.printStackTrace();
        }
        
        //SETANDO A HORA E O MINUTO
        String[] horaMinuto = tbAgendamentos.getModel().getValueAt(linha, 4).toString().split(":");
        txtHora.setText(horaMinuto[0]);
        txtMinuto.setText(horaMinuto[1]);
        
    }//GEN-LAST:event_tbAgendamentosMousePressed

    private void jButton1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MousePressed
        Agendamento ag = new Agendamento();
        ContasReceber cr = new ContasReceber();
     
        ag.setCodAgendamento(Integer.parseInt(codAg));
        ctrAgendamento.atualizarConsulta(ag);
        
        String [] paciente = cbPacientes.getSelectedItem().toString().split("-");
        cr.setHistorico("Valor referente a consulta do paciente "+paciente[1]);
        cr.setValor(180);
        ctrCR.registrarCR(cr);
        
        cbPacientes.setSelectedItem(0);
        cbDentistas.setSelectedItem(0);
        txtHora.setText("");
        txtMinuto.setText("");  
        
        ArrayList<AgendamentoVO> lista = ctrAgendamento.obterAgendamentos();
        carregarTabela(lista);
    }//GEN-LAST:event_jButton1MousePressed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btAlterarMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btAlterarMousePressed
        Agendamento ag = new Agendamento();
        
        String dadosDentista[] = cbDentistas.getSelectedItem().toString().split("-");
        String dadosPaciente[] = cbPacientes.getSelectedItem().toString().split("-");
        
        ag.setCroDentista(Integer.parseInt(dadosDentista[0]));
        ag.setCodPaciente(Integer.parseInt(dadosPaciente[0]));
        ag.setData((Date)dtAgendamento.getValue());
        ag.setHora(Integer.parseInt(txtHora.getText()));
        ag.setMinuto(Integer.parseInt(txtMinuto.getText()));
        
        ag.setCodAgendamento(Integer.parseInt(codAg));
        ctrAgendamento.alterarConsulta(ag);
        cbPacientes.setSelectedItem(0);
        cbDentistas.setSelectedItem(0);
        txtHora.setText("");
        txtMinuto.setText("");  
        
        ArrayList<AgendamentoVO> lista = ctrAgendamento.obterAgendamentos();
        carregarTabela(lista);
    }//GEN-LAST:event_btAlterarMousePressed
    
    public void carregarTabela(ArrayList<AgendamentoVO> lista){
        String[] colunas = new String[]{"codAgendamento", "nomeDentista", "nomePaciente", "dataConsulta", 
                                        "horaConsulta","codPaciente", "codDentista"};
        DefaultTableModel modeloTabela = new DefaultTableModel(null, colunas);
        tbAgendamentos.setModel(modeloTabela);
        
        for(AgendamentoVO agVO:lista){
            
            String[] linha = new String[]{agVO.getCodAgendamento(), agVO.getNomeDentista(),agVO.getNomePaciente(), agVO.getDataConsulta(),
                                            agVO.getHoraConsulta(), agVO.getCodPaciente(), agVO.getCroDentista()};
            modeloTabela.addRow(linha);
            
            }
    }
    public void carregarComboPaciente(){
        ResultSet rs = ctrPaciente.obterListagemPacientes();
        try{
            while(rs.next()){
              String linha = rs.getString("codPaciente") + "-" + rs.getString("nome");                   
              cbPacientes.addItem(linha);
            }
            
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
    }
    
    public void carregarComboDentista(){
        ResultSet rs = ctrDentista.obterListagemDentistas();
        try{
          while(rs.next()){
              String linha = rs.getString("cro") + "-" + rs.getString("nome");                   
              cbDentistas.addItem(linha);
          }
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
        
    
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AgendamentoView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AgendamentoView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AgendamentoView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AgendamentoView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AgendamentoView().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAgendar;
    private javax.swing.JButton btAlterar;
    private javax.swing.JComboBox cbDentistas;
    private javax.swing.JComboBox cbPacientes;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable tbAgendamentos;
    private javax.swing.JTextField txtHora;
    private javax.swing.JTextField txtMinuto;
    // End of variables declaration//GEN-END:variables
}
